/*
 * @Description: 全宗上下文
 * @Author: Rfan
 * @Date: 2022-01-08 16:30:05
 * @LastEditTime: 2022-02-23 14:09:24
 */

import { createContext, useContext, useEffect, useReducer } from 'react';
import { ADD_LEVEL_BY_ID } from '../constants';
import { AccessionReducer } from '../reducers/AccessionReducer';
import { fetchLevelByATId } from '@/api/archivesType';

const initialState = {
  fondsList: [],
  ATList: [],
  levelList: [],
  // 层级tab列表
  tabList: [],
  // 当前全宗OBJ
  currentFond: {},
  // 当前档案类型ID
  currentAt: 0,
  // 当前级别ID
  currentLevel: '1'
};

const AccessionContext = createContext();

const AccessionContextProvider = (props) => {
  const [state, dispatch] = useReducer(AccessionReducer, initialState);

  const actions = {
    /**
     * @description: 获取档案类型下所有层级
     * @param {number} id
     */
    async fetchATLevel(id) {
      const res = await fetchLevelByATId(id);
      const { data } = res;
      dispatch({ type: ADD_LEVEL_BY_ID, data, id });
    }
  };

  useEffect(() => {}, []);

  return (
    <AccessionContext.Provider value={{ ...state, ...actions }}>
      {props.children}
    </AccessionContext.Provider>
  );
};

export const useAccessionContext = () => {
  return useContext(AccessionContext);
};

export { AccessionContext, AccessionContextProvider };
